import datetime
from contextlib import contextmanager

from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
from sqlalchemy import Column, DateTime, Boolean


class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            raise e


db = SQLAlchemy()


class Base(db.Model, UserMixin):
    __abstract__ = True
    create_time = Column(DateTime, default=datetime.datetime.now)
    is_delete = Column(Boolean, default=False)
